#include<cstdio>
#include<iostream>
#include<pthread.h>
#include<string>
#include <unistd.h>
#include"Mutex.hpp"

int tickets=1000;

struct data{
    std::string name;
    pthread_mutex_t *lockp;
};

void* route(void* args)
{
    data *d=static_cast<data*>(args);
    while(1)
    {
        pthread_mutex_lock(d->lockp);//加锁
        if(tickets>0)
        {
            //抢票
            usleep(10000);
            printf("%s 抢占票号：%d\n",(d->name).c_str(),tickets--);
            pthread_mutex_unlock(d->lockp);//解锁
        }
        else{
            pthread_mutex_unlock(d->lockp);
            break;
        }
    }
    return (void*)0;
}
int main()
{
    pthread_mutex_t lock;
    pthread_mutex_init(&lock,nullptr);

    pthread_t t1,t2,t3,t4;
    data d1={"thread -1",&lock};
    pthread_create(&t1,nullptr,route,(void*)&d1);

    data d2={"thread -2",&lock};
    pthread_create(&t2,nullptr,route,(void*)&d2);

    data d3={"thread -3",&lock};
    pthread_create(&t3,nullptr,route,(void*)&d3);

    data d4={"thread -4",&lock};
    pthread_create(&t4,nullptr,route,(void*)&d4);


    pthread_join(t1,nullptr);
    pthread_join(t2,nullptr);
    pthread_join(t3,nullptr);
    pthread_join(t4,nullptr);

    pthread_mutex_destroy(&lock);
}